package com.book.web;

import com.book.pojo.User;
import com.book.service.Impl.userServiceImpl;
import com.book.service.userService;
import com.book.utils.webUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class userServlet extends baseServlet{
    userService userService=new userServiceImpl();

    protected void login(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = new User();
        //一次性填充所有的参数
        webUtils.fillBean(user,request.getParameterMap());

        User login = userService.login(user);
        if(login!=null){
            request.getRequestDispatcher("/pages/user/login_success.jsp").forward(request, response);
        }else {
            request.setAttribute("msg", "用户名或密码输入错误");
            request.setAttribute("username", username);
            request.getRequestDispatcher("/pages/user/login.jsp").forward(request, response);
        }
    }
    protected void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String code = request.getParameter("code");

        //检查验证码
        if ("abcd".equalsIgnoreCase(code)) {
            //正确
            //检查用户是否可用
            if (userService.existUsername(username)) {
                request.setAttribute("msg", "用户名已存在");
                request.setAttribute("username", username);
                request.setAttribute("email", email);
                request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response);
            } else {
                //可用 保存在数据库
                userService.addUser(new User(null, username, password, email));
                //跳转页面
                request.getRequestDispatcher("/pages/user/regist_success.jsp").forward(request, response);
            }
        } else {
            //不正确
            request.setAttribute("msg", "验证码错误");
            request.setAttribute("username", username);
            request.setAttribute("email", email);
            request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response);
        }
    }

}
